package com.goal98.team.controllers

import grails.converters.XML
import grails.converters.JSON
import com.goal98.team.domain.Activity
import com.goal98.team.Constants.Events
import com.goal98.team.ResourceNotFoundException
import com.goal98.grails.plugin.account.domain.Debit
import com.goal98.team.Constants

class TeamActivityController {

    def index = { }
    def myteamService
    def activityService

    def list = {
        def team = myteamService.getMyteam()
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.cache = true
        def activityInstanceTotal = Activity.executeQuery("select count(*) from Activity as a where a.team = ?", [team])?.get(0)
        def model = [activityInstanceList: Activity.findAllByTeam(team, params),
                activityInstanceTotal: activityInstanceTotal]
        withFormat {
            html {
                return model
            }
            xml {
                render model as XML
            }
            json {
                render model as JSON
            }
        }


    }

    def create = {
        def activityInstance = new Activity()
        activityInstance.properties = params
        activityInstance.team = myteamService.getMyteam()
        return ['activityInstance': activityInstance]
    }

    def save = {
        def bindData = params.activity ? params.activity : params
        def activityInstance = new Activity(bindData)
        if (!activityInstance.hasErrors() && activityInstance.save()) {
            Activity.index(activityInstance)
            final String createSucessMsg = "Activity ${activityInstance.id} created"
            withFormat {
                form {
                    flash.message = createSucessMsg
                    redirect(action: show, id: activityInstance.id)
                }
                xml {
                    response.status = 201 //created
                    render activityInstance as XML
                }
                json {
                    response.status = 201 //created
                    render activityInstance as JSON
                }
            }


        }
        else {
            withFormat {
                form {
                    render(view: 'create', model: [activityInstance: activityInstance])
                }
                xml {
                    response.status = 500
                    render activityInstance.errors as XML
                }
                json {
                    response.status = 500
                    render activityInstance.errors as JSON
                }
            }

        }
    }

    def update = {
        def activityInstance = Activity.get(params.id)
        if (activityInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (activityInstance.version > version) {
                    withFormat {
                        form {

                            activityInstance.errors.rejectValue("version", "activity.optimistic.locking.failure", "Another user has updated this Activity while you were editing.")
                            render(view: 'edit', model: [activityInstance: activityInstance])
                        }

                        xml {
                            response.status = 500
                            render activityInstance.errors as XML
                        }
                        json {
                            response.status = 500
                            render activityInstance.errors as JSON
                        }

                    }

                }
            }
            activityInstance.properties = params
            if (!activityInstance.hasErrors() && activityInstance.save()) {
                final String updateSuccessMsg = "Activity ${params.id} updated"
                withFormat {
                    form {
                        flash.message = updateSuccessMsg
                        redirect(action: show, id: activityInstance.id)
                    }
                    xml {
                        render activityInstance as XML
                    }
                    json {
                        render activityInstance as JSON
                    }
                }


            }
            else {
                withFormat {
                    form {
                        render(view: 'edit', model: [activityInstance: activityInstance])
                    }
                    xml {
                        response.status = 500
                        render activityInstance.errors as XML
                    }
                    json {
                        response.status = 500
                        render activityInstance.errors as JSON
                    }
                }

            }
        }
        else {
            final String updateNotFoundMsg = "Activity not found with id ${params.id}"
            withFormat {
                form {
                    flash.message = updateNotFoundMsg
                    redirect(action: edit, id: params.id)
                }
                xml {
                    response.status = 404
                    render(view: "/errorxml",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(updateNotFoundMsg)])
                }
                json {
                    response.status = 404
                    render(view: "/errorjson",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(updateNotFoundMsg)])
                }
            }

        }
    }

    def show = {
        def activityInstance = Activity.get(params.id)

        if (!activityInstance) {
            final notFoundMessage = "Activity not found with id ${params.id}"
            withFormat {
                html {

                    flash.message = notFoundMessage
                    redirect(action: list)
                }
                xml {
                    response.status = 404
                    render(view: "/errorxml",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(notFoundMessage)])
                }
                json {
                    response.status = 404
                    render(view: "/errorjson",
                            model: [errorCode: "404",
                                    exception: new ResourceNotFoundException(notFoundMessage)])
                }
            }

        }
        else {
            withFormat {
                html {
                    return [activityInstance: activityInstance]
                }
                xml {
                    render activityInstance as XML
                }
                json {
                    render activityInstance as JSON
                }
            }

        }
    }

    def edit = {
        def activityInstance = Activity.get(params.id)

        if (!activityInstance) {
            flash.message = "Activity not found with id ${params.id}"
            redirect(action: list)
        }
        else {
            return [activityInstance: activityInstance]
        }
    }

    def addCost = {
        Activity activity = Activity.get(params.activityId)
        Debit debit = new Debit(params)
        if (!debit.hasErrors()) {
            activityService.addCost(activity, debit)
            render message(code: 'activity.addCost.success', 'default': 'Cost Added.')
        } else {
            response.status = 500
            render message(code: 'activity.addCost.fail', 'default': 'Failed.')
        }

    }

    def costsAjax = {
        Activity activity = Activity.get(params.activityId)
        def costs = activity.costs?activity.costs:[]
        List sortedCosts = []
		for (cost in costs) {
			sortedCosts << cost
		}
		sortedCosts.sort { n1, n2 ->
			n1.id <=> n2.id
		}
        def result = [totalCost:activity.totalCost, costs:sortedCosts, costOfEachPerson:activity.costOfEachPerson]
        render result as JSON
    }

    def attendPersonAjax = {
        Activity activity = Activity.get(params.activityId)
        def personAttend = activity.personAttend

        List sortedPersonAttend = []
		for (member in personAttend) {
			sortedPersonAttend << member
		}
		sortedPersonAttend.sort { n1, n2 ->
			n1.id <=> n2.id
		}

        def result = [actualPersonCount:activity.actualPersonCount, costOfEachPerson:activity.costOfEachPerson,'peopleAttend': sortedPersonAttend]

        render result as JSON
    }

    def updateAttendPeopleAjax = {

        if(params.peopleAttendIds && !params.peopleAttendIds instanceof List){
            params.peopleAttendIds = [params.peopleAttendIds]
        }
        activityService.updateAttendPerson(params.activityId, params.peopleAttendIds)
        render "Done"
    }

    def attendPersonCheckboxes = {
        def activityInstance = Activity.get(params.id)
        def members = activityInstance.team.members
        List sortedMembers = []
		for (member in members) {
			sortedMembers << member
		}
		sortedMembers.sort { n1, n2 ->
			n1.id <=> n2.id
		}
        [activityInstance:activityInstance, members: sortedMembers]
    }

    def debitAttendPerson = {
        Activity activity = Activity.get(params.activityId)
        activityService.debitAttendPerson(activity)
        publishEvent(Constants.Events.ACTIVITY_COST_DEBITED.toString(), [activity:activity])
        render message(code: 'activity.debit.success', 'default': 'Debit done!')
    }

}
